package com.youhome.controller;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.JSMSClient;
import cn.jsms.api.ValidSMSResult;
import com.youhome.config.OSSConfig;
import com.youhome.config.SMSConfig;
import com.youhome.model.Client;
import com.youhome.model.User;
import com.youhome.response.Result;
import com.youhome.response.ResultCode;
import com.youhome.service.ClientService;
import com.youhome.service.TokenService;
import com.youhome.service.UploadService;
import com.youhome.service.UserService;
import com.youhome.utils.DateUtils;
import com.youhome.utils.TokenUtils;
import com.youhome.utils.ValidatorUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by chen365 on 2018/12/11.
 */
@RestController
@RequestMapping(value = "/user")
@Api(tags = "用户")
public class UserController {
    @Autowired
    private OSSConfig ossConfig;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserService userService;
    @Autowired
    private SMSConfig smsConfig;
    @Autowired
    private ClientService clientService;
    @Autowired
    private UploadService uploadService;

    @ApiOperation(value = "上传头像", notes = "上传头像", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/upload")
    public Object upload(HttpServletRequest request, @ApiParam(value = "头像") MultipartFile file) {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkToken(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        User currentUser = userService.getCurrentUser(openid);
        Client client = clientService.selectByUserId(currentUser.getUserId());
        if (client == null) {
            return new Result<>(ResultCode.NOT_FILLED_CLIENT_INFO);
        }

        String path = uploadService.upload(file, "upload");
        if (!StringUtils.isEmpty(path)) {
            Client entity = new Client();
            entity.setClientId(client.getClientId());
            entity.setPhoto(path);
            if (clientService.updateByPrimaryKeySelective(entity) > 0) {
                return new Result<>(ResultCode.SUCCESS, ossConfig.getDomain() + "/" + path);
            }
        }
        return new Result<>(ResultCode.FAIL);
    }

    @ApiOperation(value = "获取用户信息", notes = "获取用户信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/info")
    public Object info(HttpServletRequest request) {

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkToken(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        User currentUser = userService.getCurrentUser(openid);
        Client client = clientService.selectByUserId(currentUser.getUserId());
        if (client == null) {
            return new Result<>(ResultCode.NOT_FILLED_CLIENT_INFO);
        }
        return new Result<>(ResultCode.SUCCESS, client);
    }

    @ApiOperation(value = "修改用户信息", notes = "修改用户信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({

            @ApiImplicitParam(dataType = "String", name = "name", value = "名字", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "email", value = "邮箱", paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "weChat", value = "微信号", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "qq", value = "QQ", paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "investmentObjective", value = "投资目的", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "capitalSource", value = "资金来源，国内资金，海外资金", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyRoom", value = "房型倾向", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySite", value = "地点倾向", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyPrice", value = "价格倾向", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySize", value = "面积倾向", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySchool", value = "学校倾向(幼儿园,小学,初中,高中,大学)", paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "province", value = "省", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "city", value = "市", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "area", value = "区", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "address", value = "详细地址", paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "birthDate", value = "生日", paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "marital", value = "婚姻，0保密，1已婚，2未婚，3离异", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "income", value = "年收入", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobTitle", value = "职称", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobType", value = "工作行业", paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "gender", value = "性别，0女，1男", paramType = "query")
    })
    @PostMapping(value = "/update")
    public Object update(HttpServletRequest request, String name, String email, String weChat, String qq,
                         String investmentObjective, String capitalSource, String tendencyRoom,
                         String tendencySite, String tendencyPrice, String tendencySize, String tendencySchool,
                         String province, String city, String area, String address,
                         String birthDate, Integer marital, String income, String jobTitle, String jobType, Integer gender) {

        if (StringUtils.isEmpty(name)) {
            return new Result<>(ResultCode.EMPTY_NAME);
        }
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkToken(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        User user = userService.getCurrentUser(openid);
        //判断手机号是否已经注册
        if (user == null) {
            return new Result<>(ResultCode.UNBOUND_PHONE);
        }
        Client entity = clientService.selectByUserId(user.getUserId());

        Client client = new Client();
        if (entity != null) {
            client.setClientId(entity.getClientId());
        } else {
            client.setUserId(user.getUserId());
            client.setPhone(user.getPhone());
        }

        client.setName(name);
        client.setEmail(email);
        client.setWeixin(weChat);
        client.setQq(qq);
        client.setInvestmentObjective(investmentObjective);
        client.setCapitalSource(capitalSource);
        client.setTendencyRoom(tendencyRoom);
        client.setTendencySite(tendencySite);
        client.setTendencyPrice(tendencyPrice);
        client.setTendencySize(tendencySize);
        client.setTendencySchool(tendencySchool);
        client.setProvince(province);
        client.setCity(city);
        client.setArea(area);
        client.setAddress(address);

        if (!StringUtils.isEmpty(birthDate)) {
            Date date = DateUtils.StrToDate(birthDate, "yyyy-MM-dd");
            client.setBirthdate(date);
        }

        client.setMarital(marital);
        client.setIncome(income);
        client.setJobTitle(jobTitle);
        client.setJobType(jobType);
        client.setSex(gender);

        if (clientService.save(client) > 0) {
            return new Result<>(ResultCode.SUCCESS);
        } else {
            return new Result<>(ResultCode.FAIL);
        }
    }

    @ApiOperation(value = "绑定手机号", notes = "绑定手机号", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机号", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgCode", value = "短信验证码", required = true, paramType = "query")
    })
    @PostMapping(value = "/binding-phone")
    public Object bindingPhone(HttpServletRequest request, String phone, String msgId, String msgCode) {
        if (StringUtils.isEmpty(phone)) {
            return new Result<>(ResultCode.EMPTY_PHONE);
        }
        if (!ValidatorUtils.isPhone(phone)) {
            return new Result<>(ResultCode.PHONE_ERROR);
        }

        if (StringUtils.isEmpty(msgId)) {
            return new Result<>(ResultCode.EMPTY_MSG_ID);
        }

        if (StringUtils.isEmpty(msgCode)) {
            return new Result<>(ResultCode.EMPTY_MSG_CODE);
        }

        if (!ValidatorUtils.isNumeric(msgCode) || msgCode.length() != 6) {
            return new Result<>(ResultCode.FORMAT_MSG_CODE);
        }

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkToken(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        System.err.println("============================msgId:"+msgId+", msgCode:"+msgCode+"==================================");
        try {
            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            ValidSMSResult result = jsmsClient.sendValidSMSCode(msgId, msgCode);
            System.err.println("result:"+result.toString());
            System.err.println("result:"+result.getIsValid());
            if (!result.getIsValid()) {
                return new Result(ResultCode.ERROR_VALIDATE_CODE);
            }
        } catch (APIConnectionException e) {
            return new Result(ResultCode.NETWORK_CONNECTION_FAILED);
        } catch (APIRequestException e) {
            return new Result(ResultCode.VALIDATE_REQUEST_FAILED);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL);
        }

        User user = userService.selectByPhone(phone);
        //判断手机号是否已经注册
        if (user != null) {
            //手机号未与openid 绑定
            if (StringUtils.isEmpty(user.getOpenid())) {
                User entity = new User();
                entity.setUserId(user.getUserId());
                entity.setOpenid(openid);
                int success = userService.updateByPrimaryKeySelective(entity);
                if (success > 0) {
                    return new Result<>(ResultCode.SUCCESS);
                } else {
                    return new Result<>(ResultCode.PHONE_BINDING_FAILED);
                }
            } else {
                return new Result<>(ResultCode.IS_BINDING_PHONE);
            }
        }else {
            //注册手机号
            user = new User();
            user.setPhone(phone);
            user.setOpenid(openid);
            user.setCtime(new Date());
            user.setReportCount(0);
            user.setEnabled(true);

            int success = userService.insert(user);
            if (success == 0) {
                return new Result<>(ResultCode.PHONE_BINDING_FAILED);
            }else{
                return new Result<>(ResultCode.SUCCESS);
            }
        }
    }


    @ApiOperation(value = "退出登陆", notes = "退出登陆", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/logout")
    public Object logout(HttpServletRequest request) {

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkToken(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        tokenService.cleanToken(token, openid);

        return new Result<>(ResultCode.SUCCESS);
    }
}
